package com.company.dfs;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/number-of-islands/
 * @date 2019/11/25 16:00
 * 给定一个由 '1'（陆地）和 '0'（水）组成的的二维网格，计算岛屿的数量。一个岛被水包围，并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
 *
 * 示例 1:
 *
 * 输入:
 * 11110
 * 11010
 * 11000
 * 00000
 *
 * 输出: 1
 * 示例 2:
 *
 * 输入:
 * 11000
 * 11000
 * 00100
 * 00011
 *
 * 输出: 3
 */
public class NumIslands {

    public void dfs(char[][] grid,int i,int j) {
        int x = grid.length;
        int y = grid[0].length;

        if (i < 0 || j < 0 || i>= x || j >= y || grid[i][j] == '0') return;

        grid[i][j] = '0';

        dfs(grid,i - 1,j);
        dfs(grid,i + 1,j);
        dfs(grid,i ,j - 1);
        dfs(grid,i,j + 1);
    }


    public int numIslands(char[][] grid) {
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    res++;
                    dfs(grid,i,j);
                }
            }
        }
        return res;
    }

}
